#include "editorwindow.h"
#include "ui_editorwindow.h"
#include "Render/renderwidget.h"
#include "Narration/narrationwidget.h"
#include <QButtonGroup>
#include "GameUI/gameuicontainer.h"
EditorWindow::EditorWindow():ui(new Ui::EditorWindow)
{
    Init();
}

EditorWindow &EditorWindow::Instance()
{
    static EditorWindow instance;
    return instance;
}

EditorWindow::~EditorWindow()
{
    delete ui;
    delete settingWidget;
    delete renderWidget;
    delete filePreviewWidget;
    delete resourceWidget;
    delete narrativeDockWidget;
    delete btnGroup;
    delete menuWidget;
    delete uiEditWidget;
    delete filePreviewWidgetParent;
    delete imageEditWidget;
}

void EditorWindow::keyPressEvent(QKeyEvent *event)
{
    //用于代码调试，输出所有数据
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_D)
    {
        QMap<QString,int> i = GameData::Instance().intData;
        QMap<QString,QString> s = GameData::Instance().stringData;
        QMap<QString,float> f = GameData::Instance().floatData;
        QMap<QString,bool> b = GameData::Instance().boolData;
        qDebug()<<"游戏数值-整数：";
        for (QMap<QString,int>::const_iterator it = i.constBegin(); it != i.constEnd(); it++)
        {
            qDebug()<<it.key()<<" :"<<it.value()<<endl;
        }
        qDebug()<<"游戏数值-字符串：";
        for (QMap<QString,QString>::const_iterator it = s.constBegin(); it != s.constEnd(); it++)
        {
            qDebug()<<it.key()<<" :"<<it.value()<<endl;
        }
        qDebug()<<"游戏数值-浮点数：";
        for (QMap<QString,float>::const_iterator it = f.constBegin(); it != f.constEnd(); it++)
        {
            qDebug()<<it.key()<<" :"<<it.value()<<endl;
        }
        qDebug()<<"游戏数值-布尔值：";
        for (QMap<QString,bool>::const_iterator it = b.constBegin(); it != b.constEnd(); it++)
        {
            qDebug()<<it.key()<<" :"<<it.value()<<endl;
        }
    }
    if(EventCenter::Instance().GetApplicationMode())
        return;
    //编辑模式
    if(event->key() == Qt::Key_Delete)
    {
        if(renderWidget && renderWidget->chosen)
        {
            RenderTarget* rt = renderWidget->chosen;
            renderWidget->chosen = nullptr;
            emit renderWidget->ChosenChange(nullptr);
            int layer = rt->GetLayer();
            GameManager::Instance().curNode->RemoveImage(layer);
            GameManager::Instance().ShowNarration(GameManager::Instance().curNode);
        }
    }
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
    {
        emit EventCenter::Instance().Save();
        NarrationTree::Instance().SaveTree();
        this->setWindowTitle("MyGame-" + GameManager::Instance().name);
    }
}

void EditorWindow::Init()
{
    ui->setupUi(this);
    InitWidgets();
    InitToolBtns();
    InitHideUI();
    InitMenuBtns();

    this->setWindowTitle("MyGame-" + GameManager::Instance().name);
    this->setWindowIcon(QIcon(":/res/icon/myGame.png"));
    this->setMinimumSize(minWidth,minHeight);

    connect(&EventCenter::Instance(),&EventCenter::Modify,this,[=](){
        if(EventCenter::Instance().GetApplicationMode())
            return;
        QString name = this->windowTitle();
        if(name[name.count() - 1] != '*')
            this->setWindowTitle(name + '*');
    });
    connect(&EventCenter::Instance(),&EventCenter::ChangeWindowName,[=](QString name){
        bool star = windowTitle().count() > 0 && windowTitle().at(windowTitle().count() - 1) == '*';
        if(star)
            this->setWindowTitle(name + "*");
        else
            this->setWindowTitle(name);
    });
    connect(&EventCenter::Instance(),&EventCenter::RunGame,[=](){
        RunAsAGame();
    });
}

void EditorWindow::InitWidgets()
{
    //ui编辑窗口
    uiEditWidget = new UIEditorWidget();
    uiEditWidget->setWindowIcon(QIcon(":/res/icon/ui.png"));
    uiEditWidget->setWindowTitle("UI编辑器");

    //渲染窗口居中等大
    renderWidget = new RenderWidget();
    renderParent = new RenderParent(renderWidget);
    this->setCentralWidget(renderParent);
    GameManager::Instance().render = renderWidget;

    connect(renderWidget,&RenderWidget::ChosenChange,this,[=](RenderTarget* rt){
        imageEditWidget->ShowRenderTarget(rt);
        if(!rt)
        {
           ui->SizeBtn->setText("缩放100%");
           ui->SizeSlider->setValue(100);
           return;
        }
        float st = rt->sizeTimes;
        ui->SizeBtn->setText("缩放" + QString::number(st * 100) + "%");
        if(st <= 2 && st >= 0.01f){
            ui->SizeSlider->setValue(st * 100);
        }
        else if(st > 2)
        {
            ui->SizeSlider->setValue(200);
        }
        else
        {
            ui->SizeSlider->setValue(1);
        }
    });
    connect(renderWidget,&RenderWidget::RefreshChosen,this,[=](){
        imageEditWidget->ShowRenderTarget(renderWidget->chosen);
    });
    float minw = 400.0f;

    //如果不用q承载，filePreviewWidget的标题栏会被隐藏
    filePreviewWidgetParent = new QDockWidget(this);
    filePreviewWidgetParent->setWindowTitle("预览");
    filePreviewWidgetParent->setFeatures(QDockWidget::AllDockWidgetFeatures);
    filePreviewWidgetParent->setMinimumSize(minw,minw);
    this->addDockWidget(Qt::BottomDockWidgetArea,filePreviewWidgetParent);
    filePreviewWidgetParent->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    filePreviewWidget = new FilePreviewWidget(filePreviewWidgetParent);
    filePreviewWidgetParent->setWidget(filePreviewWidget);
    QWidget* ftb = filePreviewWidget->titleBarWidget();
    filePreviewWidget->setTitleBarWidget(new QWidget());
    delete ftb;
    ftb = nullptr;
    filePreviewWidget->setFeatures(QDockWidget::NoDockWidgetFeatures);

    resourceWidget = new ResourcesWidget();
    resourceWidget->setWindowTitle("文件");
    resourceWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    resourceWidget->setMinimumSize(minw,minw);
    this->addDockWidget(Qt::BottomDockWidgetArea,resourceWidget);
    resourceWidget->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);

    float sideW = 550.0f;
    narrativeDockWidget = new QDockWidget(this);
    narrativeDockWidget->setWindowTitle("剧情");
    narrativeDockWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    narrativeDockWidget->setMinimumSize(sideW,sideW);
    this->addDockWidget(Qt::RightDockWidgetArea,narrativeDockWidget);
    narrativeDockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    NarrationWidgetTool* narrationWidgetTool = new NarrationWidgetTool();
    narrativeDockWidget->setWidget(narrationWidgetTool);

    //工具小窗口
    menuWidget = new MenuWidget();
    menuWidget->setWindowTitle("节点编辑工具");
    menuWidget->setFeatures(QDockWidget::AllDockWidgetFeatures);
    menuWidget->setMinimumSize(sideW,sideW);
    this->addDockWidget(Qt::LeftDockWidgetArea,menuWidget);
    menuWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);

    //隐藏DockWidget标题栏
    QWidget * tmp = new QWidget();
    //工具栏
    QWidget * tb = ui->ToolBar->titleBarWidget();
    ui->ToolBar->setTitleBarWidget(tmp);
    delete tb;
    ui->ToolBar->setFeatures(QDockWidget::NoDockWidgetFeatures);

    //编辑图形
    imageEditorParent = new QDockWidget(this);
    imageEditWidget = new ImageEditWidget(imageEditorParent);

    imageEditorParent->setWidget(imageEditWidget);
    imageEditorParent->setWindowTitle("图片详情");
    imageEditorParent->setFeatures(QDockWidget::AllDockWidgetFeatures);
    this->addDockWidget(Qt::BottomDockWidgetArea,imageEditorParent);
    imageEditorParent->setAllowedAreas(Qt::BottomDockWidgetArea);
}

void EditorWindow::InitToolBtns()
{
    ui->SaveBtn->setIcon(QIcon(":/res/icon/save.png"));
    ui->SearchBtn->setIcon(QIcon(":/res/icon/search.png"));
    ui->CancelBtn->setIcon(QIcon(":/res/icon/cancel.png"));
    ui->RedoBtn->setIcon(QIcon(":/res/icon/redo.png"));

    ui->SettingBtn->setIcon(QIcon(":/res/icon/setting.png"));

    ui->SizeBtn->setIcon(QIcon(":/res/icon/bigger.png"));

    ui->UIBtn->setIcon(QIcon(":/res/icon/ui.png"));
    connect(ui->UIBtn,&QPushButton::clicked,this,[=](){
        uiEditWidget->showMaximized();
    });
    connect(ui->SaveBtn,&QPushButton::clicked,this,[=](){
        emit EventCenter::Instance().Save();
        NarrationTree::Instance().SaveTree();
        this->setWindowTitle("MyGame-" + GameManager::Instance().name);
    });
    InitEditToolBtns();
}

void EditorWindow::InitMenuBtns()
{
    connect(ui->menuSave,&QAction::triggered,this,[=](){
        emit EventCenter::Instance().Save();
        NarrationTree::Instance().SaveTree();
        this->setWindowTitle("MyGame-" + GameManager::Instance().name);
    });
    connect(ui->menuRelease,&QAction::triggered,this,&EditorWindow::Release);
}

void EditorWindow::InitEditToolBtns()
{
    ui->RunBtn->setIcon(QIcon(":/res/icon/run.png"));
    connect(ui->RunBtn,&QPushButton::pressed,this,[=](){
        RunBtn(false);
    });
    ui->RunHereBtn->setIcon(QIcon(":/res/icon/runHere.png"));
    connect(ui->RunHereBtn,&QPushButton::pressed,this,[=](){
        RunBtn(true);
    });
    ui->MoveBtn->setIcon(QIcon(":/res/icon/move.png"));
    ui->MoveBtn->setCheckable(true);
    connect(ui->MoveBtn,&QPushButton::toggled,renderWidget,[=](){
        renderWidget->CursorChange(RenderWidget::MOVE_IMAGE);
    });
    ui->SelectBtn->setIcon(QIcon(":/res/icon/select.png"));
    ui->SelectBtn->setCheckable(true);
    connect(ui->SelectBtn,&QPushButton::toggled,renderWidget,[=](){
        renderWidget->CursorChange(RenderWidget::SELECT);
    });

    btnGroup = new QButtonGroup();
    btnGroup->setExclusive(true);
    btnGroup->addButton(ui->MoveBtn);
    btnGroup->addButton(ui->SelectBtn);
    ui->SelectBtn->setChecked(true);

    connect(ui->SizeSlider,&QSlider::valueChanged,this,[=](){
        ui->SizeBtn->setText("缩放" + QString::number(ui->SizeSlider->value()) + "%");
        if(this->renderWidget->chosen)
        {
            this->renderWidget->chosen->sizeTimes = (float)ui->SizeSlider->value() / 100.f;
            imageEditWidget->ShowRenderTarget(renderWidget->chosen);
            emit EventCenter::Instance().Modify();
        }
    });
}

void EditorWindow::InitHideUI()
{
    //设置
    settingWidget = new SettingWidget();
    connect(ui->SettingBtn,&QPushButton::clicked,this,[&](){
        this->settingWidget->show();
    });
}

void EditorWindow::ReleaseMode(bool release)
{
    ui->MoveBtn->setDisabled(release);
    ui->SelectBtn->setDisabled(release);
    narrativeDockWidget->setDisabled(release);
    resourceWidget->setDisabled(release);
    menuWidget->setDisabled(release);
    filePreviewWidget->setDisabled(release);
    ui->UIBtn->setDisabled(release);

    DisableSizeSlider(release);
    if(release)
    {
        renderWidget->chosen = nullptr;
        emit renderWidget->ChosenChange(nullptr);
    }
}

void EditorWindow::DisableSizeSlider(bool disable)
{
    ui->SizeBtn->setDisabled(disable);
    ui->SizeSlider->setDisabled(disable);
    if(disable)
    {
        ui->SizeBtn->setText("缩放100%");
        ui->SizeSlider->setValue(ui->SizeSlider->maximum() / 2);
    }
}

void EditorWindow::RunBtn(bool runHere)
{
    QString check_qss = "QPushButton{background-color:transparent;border:none;padding-left:10px;padding-right:10px;}";
    QString uncheck_qss = "border-top-left-radius:10px;border-top-right-radius:10px;border-bottom-right-radius:10px;border-bottom-left-radius:10px;background-color: rgb(199, 222, 255);padding-left:10px;padding-right:10px;";
    bool release = EventCenter::Instance().GetApplicationMode();
    emit EventCenter::Instance().ApplicationMode(!release);
    if(release)
    {
        GameManager::Instance().Stop();
        if(!runHere)
        {
            ui->RunBtn->setText("从头运行");
            ui->RunHereBtn->setDisabled(false);
            ui->RunBtn->setStyleSheet(check_qss);
            GameUIContainer::Instance().ChangeUI("封面");
            GameUIContainer::Instance().hide();
            SoundManager::Instance().Pause(SoundManager::BGM);
        }
        else
        {
            ui->RunHereBtn->setText("从此运行");
            ui->RunBtn->setDisabled(false);
            ui->RunHereBtn->setStyleSheet(check_qss);
        }
    }
    else
    {
        NarrationNode* node = GameManager::Instance().curNode;
        if(!runHere)
        {
            ui->RunBtn->setText("停止运行");
            ui->RunHereBtn->setDisabled(true);
            ui->RunBtn->setStyleSheet(uncheck_qss);
            GameUIContainer::Instance().ChangeUI("封面");
            GameUIContainer::Instance().show();
            SoundManager::Instance().PlayBGM(GameManager::Instance().bgmPath,true);
        }
        else
        {
            GameManager::Instance().RunNarration(node);
            ui->RunHereBtn->setText("停止运行");
            ui->RunBtn->setDisabled(true);
            ui->RunHereBtn->setStyleSheet(uncheck_qss);
        }

    }
    ReleaseMode(!release);
}

void EditorWindow::HideWidgets()
{
    menuWidget->hide();
    narrativeDockWidget->hide();
    filePreviewWidgetParent->hide();
    resourceWidget->hide();
    imageEditorParent->hide();
    ui->ToolBar->hide();
    ui->menubar->hide();
}

void EditorWindow::RunAsAGame()
{
    RunBtn(false);
    HideWidgets();
    this->setWindowTitle(GameManager::Instance().name);
    this->setWindowIcon(QIcon(GameManager::Instance().iconPath));
    if(GameManager::Instance().fullScreen)
        this->showFullScreen();
}

void EditorWindow::Release()
{
    //打包发布
    //选择路径
    QString path = QFileDialog::getExistingDirectory(this, "选择打包发布路径...", "./");
    if(!path.isEmpty())
    {
        //更改isGame变量
        GameManager::Instance().isGame = true;
        GameManager::Instance().Save();

        QString exePath = QCoreApplication::applicationDirPath();
        FileManager::Instance().CopyDir(path,exePath);

        QString curPath = QDir::currentPath();
        FileManager::Instance().CopyDir(path,curPath);

        //还原isGame变量
        GameManager::Instance().isGame = false;
        GameManager::Instance().Save();
    }
}
